<!--
 * @Author: 陈伟 291456440@qq.com
 * @Date: 2022-07-18 14:45:25
 * @LastEditors: 陈伟 chenwei@duoliheng.com
 * @LastEditTime: 2023-01-10 15:22:31
 * @FilePath: \cool.front\src\views\customerCenter\getBottleReturnBottle\components\RealCsmTab.vue
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
-->
<template>
  <div>
    <!-- 领瓶 -->
    <el-table-form ref="form" :model="query">
      <el-form-item :table-form-merge="2" class="merge-item">
        <el-select v-model="dateType" style="width: 170px; margin-right: 2px;">
          <el-option label="领瓶时间" value="operatorTime" />
          <el-option label="审核时间" value="auditTime" />
          <!-- <el-option label="最后订气时间" value="lastBuyDt" /> -->
        </el-select>
        <el-date-picker
          v-model="date"
          clearable
          type="datetimerange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          unlink-panels
          :default-time="['00:00:00', '23:59:59']"
        />
      </el-form-item>
      <el-form-item label="所属机构:" prop="orgSNNo">
        <el-tree-select
          v-model="query.orgSNNo"
          clearable
          class="tree-select"
          :popover-width="360"
          :select-params="{
            clearable: true,
            placeholder: '请选择',
          }"
          :tree-params=" {
            'expand-on-click-node': false,
            'highlight-current': true,
            'filterable': true,
            props:{
              value:'orgSNNo',
              label: 'orgName',
              disabled: 'disabled',
            },
            data: treeData
          }"
          @node-click="selectTreeChange"
          @select-clear="handleClear"
        />
      </el-form-item>
      <el-form-item label="配送员名称:" prop="csmType">
        <el-select v-model="query.userIdList" clearable filterable multiple collapse-tags style="width: 100%;" placeholder="请选择">
          <el-option
            v-for="(item,index) in ownersList"
            :key="index"
            :label="item.userName"
            :value="item.userId"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="状态:" prop="billStatus">
        <el-select v-model="query.billStatus" clearable placeholder="请选择">
          <el-option
            v-for="item in billStatusMap"
            :key="item.value"
            :label="item.desc"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <template v-slot:btns>
        <el-button v-permission="[70101,1]" type="primary" icon="el-icon-search" @click="search">查询</el-button>
      </template>
    </el-table-form>
    <div style="margin-bottom: 10px;" class="btn-group">
      <el-button
        v-permission="[70101,5]"
        type="primary"
        icon="el-icon-download"
        :loading="$loadingPlugin.batchExp"
        @click="batchExp"
      >导出</el-button>
    </div>
    <lb-table
      ref="lbTable"
      v-loading="$loadingPlugin.fetchData"
      v-el-height-adaptive-table="{bottomOffset:10}"
      border
      highlight-current-row
      element-loading-text="加载中"
      :column="column"
      :data="tableData.data"
      pagination
      :total="tableData.total"
      custom-column
      @fetch="fetchData"
    />
    <bottle-detail ref="bottleDetail" :type="1" />
    <detail ref="detail" type="get" />
    <editBottleNum ref="editBottleNum" @upDataTable="search" />
    <recovery ref="recovery" @upDataTable="search" />
    <outboundDetail ref="outboundDetail" />
    <div class="footText">查询条件下合计瓶数:{{ footerNum }}</div>
  </div>
</template>

<script>
  import { formatColumnMap, parseTime } from '@/utils'
  import { callorBottleList, csDeliverUserList, callarAudit, callorBottleExport } from '@/api'
  import { mapGetters } from 'vuex'
  import bottleDetail from './bottleDetail.vue'
  import detail from './detail.vue'
  import recovery from './recovery.vue'
  import editBottleNum from './editBottleNum.vue'
  import moment from 'dayjs'
  import outboundDetail from './outboundDetail'

  export default {
    name: 'getBottle',
    components: {
      bottleDetail, detail, recovery, editBottleNum, outboundDetail
    },
    props: {
      treeData: {
        type: Array,
        required: true
      }
    },
    data() {
      return {
        dateType: 'operatorTime',
        txt: '',
        date: [new Date(new Date().setHours(0, 0, 0, 0)), new Date(new Date().setHours(0, 0, 0, 0) + 24 * 60 * 60 * 1000 - 1)],
        updateList: [], // 批量操作
        ids: [],
        invalidStr: '',
        ownersList: [],
        searchParams: {},
        query: {
          orgSNNo: '',
          userIdList: [],
          billStatus: '',
          billType: 1
        },
        billStatusMap: [
          {
            value: 1,
            desc: '待审核'
          },
          {
            value: 2,
            desc: '已审核'
          },
          {
            value: 3,
            desc: '已驳回'
          }
        ],
        tableData: {
          total: 0,
          data: []
        },
        footerNum: 0
      }
    },
    computed: {
      ...mapGetters([
        'userInfo', 'exportDomain'
      ]),
      csmStatusMap: function() {
        return this.csmStatus.filter(item => item.value !== -1)
      },
      column: function() {
        const cols = [
          {
            type: 'index'
          },
          {
            prop: 'invenBillCode',
            label: '单号',
            width: 160,
            render: (h, { row }) => (<el-link underline={false} onClick={() => this.showDetail(row)}>{row.invenBillCode}</el-link>)

          },
          {
            prop: 'operatorTime',
            label: '领瓶时间',
            width: 160,
            render: (h, { row }) => row.operatorTime && <span>{ parseTime(row.operatorTime, '{y}-{m}-{d} {h}:{i}:{s}') }</span>
          },
          {
            prop: 'operator',
            label: '领瓶人'
          },
          {
            prop: 'orgName',
            label: '所属机构'
          },
          {
            prop: 'count1',
            label: '领瓶数量',
            render: (h, { row }) => <el-link underline={false} onClick={() => this.openDetail(row)}>{row.count1}</el-link>
          },
          {
            prop: 'auditTime',
            label: '审核时间',
            render: (h, { row }) => row.auditTime && <span>{ parseTime(row.auditTime, '{y}-{m}-{d} {h}:{i}:{s}') }</span>
          },
          {
            prop: 'auditor',
            label: '审核人'
          },
          {
            prop: 'billStatus',
            label: '状态',
            render: (h, { row }) => <span>{ row.billStatus && formatColumnMap(this.billStatusMap, 'value', row.billStatus, 'desc') }</span>
          },
          {
            prop: 'invenBillCode',
            label: '出库瓶号',
            render: (h, { row }) => (row.isScan > 0 && <el-link underline={false} onClick={() => this.openBottleDetail(row)}>查看详情</el-link>)
          },
          {
            label: '操作',
            className: 'action-col',
            width: 160,
            align: 'center',
            fixed: 'right',
            render: (h, { row, $index }) => {
              return (
                <div>
                  {<el-link v-permission={[70101, 2]} underline={false} size='mini' style={row.billStatus !== 1 ? 'color:#909399' : ''} disabled={row.billStatus !== 1} onClick={() => this.recovery(row, '不通过')}>
                    驳回
                  </el-link>}
                  {<el-link v-permission={[70101, 4]} v-show={row.billStatus === 1 && row.recordList.length} underline={false} size='mini' onClick={() => this.pass(row)}>
                    通过
                  </el-link>}
                  {<el-link v-permission={[70101, 3]} underline={false} size='mini' onClick={() => this.editNum(row)}>
                    编辑瓶号
                  </el-link>}
                </div>
              )
            }
          }
        ]
        // if (this.userInfo.corpCode !== '22016') {
        //   const csmOption3 = cols.findIndex(item => item.prop === 'csmOption3')
        //   cols.splice(csmOption3, 1)
        //   const csmOption5 = cols.findIndex(item => item.prop === 'csmOption5')
        //   cols.splice(csmOption5, 1)
        // }
        return cols
      }
    },
    methods: {
      _getQuery(obj) {
        const query = {}
        for (const key in obj) {
          if (obj.hasOwnProperty(key)) {
            if (obj[key] !== '') {
              query[key] = obj[key]
            }
          }
        }
        return query
      },
      async fetchData({ currentPage = 1, pageSize = 20 }) {
        const query = {
          json: { ...this._getQuery(this.query) },
          pageIndex: currentPage,
          pageSize
        }
        if (this.date && this.date.length === 2) {
          query.json.startTime = moment(this.date[0]).format()
          query.json.endTime = moment(this.date[1]).format()
          if (this.dateType === 'operatorTime') {
            query.json.operatorTime = moment(this.date[0]).format()
            query.json.operatorTimeEnd = moment(this.date[1]).format()
          }
          if (this.dateType === 'auditTime') {
            query.json.auditTime = moment(this.date[0]).format()
            query.json.auditTimeEnd = moment(this.date[1]).format()
          }
        }
        this.searchParams = { ...(query.json),
                              pageIndex: query.currentPage,
                              pageSize: query.pageSize }
        const res = await callorBottleList(query)
        this.tableData.data = res.data.rows
        if (res.data.footer[0]) {
          this.footerNum = res.data.footer[0].totalNum
        }
        if (currentPage === 1) this.tableData.total = res.data.total
      },
      // 选择所属机构
      selectTreeChange(value) {
        this.$set(this.query, 'userIdList', [])
        this.getOwnersList(value)
      },
      handleClear() {
        this.$set(this.query, 'userIdList', [])
        this.ownersList = []
      },
      // 查询处理人列表
      async getOwnersList(org) {
        this.ownersList = []
        const res = await csDeliverUserList({
          deliveryOrgId: org.orgId,
          deliveryOrgSNNo: org.orgSNNo
        })
        this.ownersList = res.data
      },
      // 出库瓶号详情弹窗
      async openBottleDetail(row) {
        await this.$refs.bottleDetail.open(row)
      },
      async openDetail(row) {
        await this.$refs.detail.open(row)
      },
      async recovery(row, type) {
        await this.$refs.recovery.open(row, type, 'get')
      },
      // 通过
      async pass(row) {
        const params = {
          billCode: row.invenBillCode,
          billStatus: 2
        }
        this.disabled = false
        this.$confirm('确定审核通过？', '提示', {
          type: 'warning'
        }).then(() => {
          if (!this.disabled) {
            this.disabled = true
            callarAudit(params).then(() => {
              this.$notify({
                title: '提示',
                message: '操作成功',
                type: 'success',
                duration: 2000
              })
              this.$refs.lbTable.fetch({ currentPage: 1 })
              this.disabled = false
            })
          }
        })
      },
      async showDetail(row) {
        await this.$refs.outboundDetail.open(row)
        this.search()
      },
      // 编辑瓶号
      async editNum(row) {
        await this.$refs.editBottleNum.open(row.invenBillCode)
      },
      search() {
        this.$refs.lbTable.fetch({ currentPage: 1 })
      },
      // 导出
      batchExp() {
        const _this = this
        this.$confirm(`确定导出数据？`, '提示', {
          type: 'warning'
        }).then(() => {
          const copyColumn = JSON.parse(JSON.stringify(this.column))
          const str = {}
          copyColumn.pop()
          copyColumn.forEach((item) => {
            str[item.prop] = item.label
          })
          const params = this.searchParams
          const paramInfo = _this._getQuery(params)
          callorBottleExport({
            paramInfo: paramInfo,
            kv: str // 表格列
          }).then((res) => {
            window.open(`${this.exportDomain}/page/export/frame?key=${res.data}`, '_blank')
          })
        })
      }
    }
  }
</script>

<style lang="scss" scoped>
/deep/.el-form-item {
  margin-bottom: 10px;
}
.disabled {
  color: #909399 !important;
}
.footText {
  position: absolute;
  right: 10px;
  bottom: 5px;
  color: #F56C6C;
}
</style>
